<?php
namespace app\admin\controller;
class Btccoin extends Base
{
    //列表
    public function lists(){
        if(is_post()){
            $d = request()->post();
            $map = [];
            if($d['keyword']!=''){
                $map[] = ['title','like',"%{$d['keyword']}%"];
            }
            if($d['btc_plat_id']!=''){
                $map[] = ['btc_plat_id','like',"%{$d['btc_plat_id']}%"];
            }
        	$rs = model('BtcCoin')::where($map)
                                ->with('BtcPlat')
                                ->order('sort desc,id desc')
                                ->paginate($d['limit'],false,['page'=>$d['page']]);
            if($rs){
                $rs = $rs->toArray();
                return suc($rs['data'], $rs['total']);
            }else{
                return suc([],0);
            }
        }
        $btc_plat = model('BtcPlat')->order('sort desc,id desc')->column('title','id');
        return $this->fetch('',['btc_plat'=>$btc_plat]);
    }

    //添加
    public function add(){
        if(is_post()){
            $d = request()->post();
            $rs = model('BtcCoin')->renew($d,false);
            if(isset($d['btc_plat_id'])){
                $rs->btcPlat()->saveAll($d['btc_plat_id']);
            }
            session('js.function','preload');
            return suc();
        }
        $plat = model('BtcPlat')->column('title','id');
        return $this->fetch('',['plat'=>$plat]);
    }

    //编辑
    public function edit($id=''){
        if(is_post()){
            $d = request()->post();
            $rs = model('BtcCoin')->renew($d,false);
            if(isset($d['btc_plat_id'])){
                $rs->btcPlat()->detach();
                $rs->btcPlat()->saveAll($d['btc_plat_id']);
            }
            session('js.function','preload');
            return suc();
        }
        $plat = model('BtcPlat')->column('title','id');
        $info = model('BtcCoin')::get($id);
        $checked = Db::name('btc_plat_coin')->where("btc_coin_id",$id)->column('btc_plat_id','id');
        return $this->fetch('', ['info'=>$info,'plat'=>$plat,'checked'=>$checked]);
    }
    //删除
    public function del(){
        if(is_post()){
            $d = input();
            $rs = model('BtcCoin')->del($d['id']);
            session('js.function','reload');
            if($rs){
                return suc();
            }else{
                return err(model('AdminGroup')->getError());
            }
        }
    }
    //详情
    public function detail($id){
        return $this->fetch();
    }
}
